﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using Newtonsoft.Json.Linq;
using FineUI;
using YunHan.BuShi123.BLL;
using YunHan.BuShi123.Model;
using System.Data.SqlClient;

public partial class admin_account_list : AdminBasePage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // 删除选中单元格的客户端脚本
            string deleteScript = GetDeleteScript();

            // 新增数据初始值
            JObject defaultObj = new JObject();
            btnNew.OnClientClick = Grid1.GetAddNewRecordReference(defaultObj, true);

            // 删除选中行按钮
            btnDelete.OnClientClick = Grid1.GetNoSelectionAlertReference("请至少选择一项！") + deleteScript;

            // 绑定表格
            BindGrid();
        }
    }

    // 删除选中行的脚本
    private string GetDeleteScript()
    {
        return Confirm.GetShowReference("删除选中行？", String.Empty, MessageBoxIcon.Question, Grid1.GetDeleteSelectedReference(), String.Empty);
    }

    private void BindGrid()
    {
        string Where = "";
        if (!string.IsNullOrEmpty(txtName.Text.Trim()))
        {
            Where += " Name LIKE @Name";
        }

        int R = 0;
        List<Account_Model> table = Account_BLL.GetModelListByPage(ref R, Where, "", "", Grid1.PageSize, Grid1.PageIndex + 1, new SqlParameter("@Name", "%" + txtName.Text.Trim() + "%"));
        Grid1.DataSource = table;
        Grid1.DataBind();
        Grid1.RecordCount = R;
    }

    protected void Grid1_OnPageIndexChange(object sender, FineUI.GridPageEventArgs e)
    {
        Grid1.PageIndex = e.NewPageIndex;
        BindGrid();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        Grid1.PageIndex = 0;
        BindGrid();
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        // 删除现有数据
        List<int> deletedRows = Grid1.GetDeletedList();
        foreach (int rowIndex in deletedRows)
        {
            using (System.Data.SqlClient.SqlTransaction Trans = YunHan.BuShi123.DAL.BuShi123SqlHelper.CreateSqlTransaction())
            {
                try
                {
                    int rowID = Convert.ToInt32(Grid1.DataKeys[rowIndex][0]);
                    string Name = Grid1.DataKeys[rowIndex][1].ToString();
                    Account_BLL.DeleteByKeyField(Trans, rowID);
                    Record_BLL.Delete(Trans, "Name='" + Name + "'");
                    Trans.Commit();
                }
                catch (Exception)
                {
                    Trans.Rollback();
                    FineUI.Alert.Show("删除失败，请尝试重新操作", MessageBoxIcon.Error);
                    return;
                }
            }
        }

        // 修改的现有数据
        Dictionary<int, Dictionary<string, string>> modifiedDict = Grid1.GetModifiedDict();
        foreach (int rowIndex in modifiedDict.Keys)
        {
            int rowID = Convert.ToInt32(Grid1.DataKeys[rowIndex][0]);

            string UpdateSet = "";
            List<SqlParameter> Parms = new List<SqlParameter>();
            Parms.Add(new SqlParameter("@ID", rowID));

            if (modifiedDict[rowIndex].ContainsKey("Name"))
            {
                UpdateSet += ",Name=@Name";
                Parms.Add(new SqlParameter("@Name", modifiedDict[rowIndex]["Name"].ToString().Trim()));
            }

            if (modifiedDict[rowIndex].ContainsKey("Url"))
            {
                UpdateSet += ",Url=@Url";
                Parms.Add(new SqlParameter("@Url", modifiedDict[rowIndex]["Url"].ToString().Trim()));
            }

            if (modifiedDict[rowIndex].ContainsKey("Address"))
            {
                UpdateSet += ",Address=@Address";
                Parms.Add(new SqlParameter("@Address", modifiedDict[rowIndex]["Address"].ToString().Trim()));
            }

            if (modifiedDict[rowIndex].ContainsKey("QQ"))
            {
                UpdateSet += ",QQ=@QQ";
                Parms.Add(new SqlParameter("@QQ", modifiedDict[rowIndex]["QQ"].ToString().Trim()));
            }

            if (modifiedDict[rowIndex].ContainsKey("Notes"))
            {
                UpdateSet += ",Notes=@Notes";
                Parms.Add(new SqlParameter("@Notes", modifiedDict[rowIndex]["Notes"].ToString().Trim()));
            }

            if (UpdateSet.Length > 0)
            {
                UpdateSet = UpdateSet.Remove(0, 1);
            }
            else
            {
                FineUI.Alert.Show("没有任何修改项");
                return;
            }

            Account_BLL.Update(UpdateSet, "ID=@ID", Parms.ToArray());
        }


        // 新增数据
        List<Dictionary<string, string>> newAddedList = Grid1.GetNewAddedList();
        for (int i = 0; i < newAddedList.Count; i++)
        {
            Account_BLL.Add(new Account_Model()
            {
                Address = newAddedList[i]["Address"].ToString(),
                Name = newAddedList[i]["Name"].ToString(),
                LastID = 0,
                LastUpdateTime = Convert.ToDateTime("1970-01-01"),
                Notes = newAddedList[i]["Notes"].ToString(),
                QQ = newAddedList[i]["QQ"].ToString(),
                Url = newAddedList[i]["Url"].ToString(),
                ViewNum = 0,
                YupooAccount = ""
            });
        }


        //labResult.Text = "用户修改的数据：" + Grid1.GetModifiedData().ToString(Newtonsoft.Json.Formatting.None);

        BindGrid();

        FineUI.PageContext.RegisterStartupScript(Grid1.GetCommitChangesReference());

        Alert.Show("数据保存成功！");
    }

}